package com.google.android.exoplayer.upstream;

import android.util.Log;

import com.sct.rtsp.RTSPJni;

/**
 * Created by chenc on 7/6/16.
 */
public class RTSPDataSource implements UriDataSource {

    private final TransferListener listener;

    private String uriString;
    private boolean opened;

    private byte[] mCached;
    private int mIndex;


    public RTSPDataSource() {
        this(null);
    }
    public RTSPDataSource(TransferListener listener) {
        this.listener = listener;
    }

    @Override
    public long open(DataSpec dataSpec){

        mCached = new byte[188];
        mIndex = 188;///none data

        uriString = dataSpec.uri.toString();
        ///open rtsp here
        Log.v("sct", "rtsp uri:" + uriString);
        RTSPJni.create();
        RTSPJni.setUrl(uriString);

        opened = true;
        if (listener != null) {
            listener.onTransferStart();
        }

        return dataSpec.length;
    }

    @Override
    public int read(byte[] buffer, int offset, int readLength){
        int left = 0;
        int ret = 0;

        while (true) {
            left = 188 - mIndex;

            if (left > 0) {
                break;
            }

            //read from rtsp
            ret = RTSPJni.getData(mCached, 188);
            //Log.v("sct", String.format("read from rtsp:%d", ret));
            if (ret > 0) {
                mIndex = 0;
            } else {
                return 0;
            }
        }

        ///now all right
        ret = Math.min(left, readLength);
        System.arraycopy(mCached, mIndex, buffer, offset, ret);

        mIndex += ret;

        if (listener != null) {
            listener.onBytesTransferred(ret);
        }

        return ret;
    }

    @Override
    public String getUri() {
        return uriString;
    }

    @Override
    public void close() {
        uriString = null;
        mCached = null;

        ///close rtsp here
        RTSPJni.destroy();

        if (opened) {
            opened = false;
            if (listener != null) {
                listener.onTransferEnd();
            }
        }
    }

}
